import SwiftUI

struct Post: Identifiable {
  let id = UUID()
  let image: String
  let body: String
//  let user:IndexUser
//  init(image: String, body: String, user: IndexUser) {
//            self.image = image
//            self.body = body
//            self.user = user
//        }
}

struct IndexUser: Codable {
  let userName: String
  let avatarUrl: String
}

struct IndexView: View {
    @State var isLoading = false
    @State private var remoteImage : UIImage? = nil
    let placeholderOne = UIImage(named: "Picture") //占位图
    
    func fetchRemoteImage(urlString:String) //用来下载互联网上的图片
        {
            guard let url = URL(string: urlString) else { return } //初始化一个字符串常量，作为网络图片的地址
            URLSession.shared.dataTask(with: url){ (data, response, error) in //执行URLSession单例对象的数据任务方法，以下载指定的图片
                if let image = UIImage(data: data!){
                    self.remoteImage = image //当图片下载成功之后，将下载后的数据转换为图像，并存储在remoteImage属性中
                }
                else{
                    print(error ?? "") //如果图片下载失败之后，则在控制台输出错误信息
                }
            }.resume() //通过执行resume方法，开始下载指定路径的网络图片
        }
    
    let user1 = IndexUser(userName: "John Doe", avatarUrl: "https://example.com/avatar.jpg")
    
    @State var posts: [Post] = []
    // @StateObject var indexProvider = IndexProvider()
    
    func getPost(){
        posts=[]
        isLoading = true
      //  print(123)
        index_provider.request(.getPost)
        { result in
            switch result {
            case let .success(response):
                do {
                    let decodedSkinData = try JSONDecoder().decode(PostResponse.self, from: response.data)
               //     print(decodedSkinData)
                    
                    for skinData in decodedSkinData.content {
                        
                        let httpsURLString = skinData.urls[0].replacingOccurrences(of: "http://", with: "https://")
                        print(httpsURLString)
                        let post = Post(image: httpsURLString, body: skinData.body)
                        posts.append(post)
                        isLoading = false
                    }
                    
                    
                    
                }catch let error{
                    print(error)
                }
            case let .failure(error):
                print(error)
            }
        }
    }
    //    func getPost(){
    //            print(123)
    //            indexProvider.requestPosts() { result in
    //                switch result {
    //                case let .success(posts):
    //                    self.posts = posts
    //                    print(posts)
    //                case let .failure(error):
    //                    print(error)
    //                }
    //            }
    //        }
    
    
    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible())
    ]
    
    var body: some View {
        VStack{
            ZStack {
                Rectangle()
                    .fill(Color.white)
                    .frame(height: 40)
                
                HStack{
                    NavigationLink(destination: postBlog()) {
                        Image(systemName: "plus")
                            .font(.system(size: 32))
                            .padding(.leading)
                            .foregroundColor(Color.primary)
                    }
                    Spacer()
                    Text("关注")
                    Spacer()
                    Text("推荐")
                    Spacer()
                    Text("好友")
                    Spacer()
                    Image(systemName: "magnifyingglass")
                    //.frame(width: 36, height: 36)
                        .font(.system(size: 32))
                        .padding(.trailing)
                }
            }.background(Color.white)
            
            ScrollView {
                LazyVGrid(columns: columns, spacing: 16) {
                    ForEach(posts) { post in
                        NavigationLink(destination: PostDetailView(post: post)) {
                            VStack(alignment: .leading) {
                                //没加载出来之前显示加载中
                                returnImg(urlString:  post.image)
                                        .resizable()
//                                        .aspectRatio(contentMode: .fit)
                                        .frame(height: 200)
                                
                                Text(post.body)
                                    .font(.headline)
                                    .foregroundColor(.primary)
                                    .lineLimit(1)
                                    .padding(.leading)
                                HStack{
                                    Image("icon")
                                        .resizable()
                                        .aspectRatio(contentMode: .fit)
                                        .frame(width:36,height:36)
                                    VStack{
                                        Text("这里是用户名")
                                            .font(.system(size: 12))
                                            .foregroundColor(.gray)
                                        Text("这里是时间")
                                            .font(.system(size: 12))
                                            .foregroundColor(.gray)
                                    }
                                }.padding(.leading)
                            }
                            .background(Color.white)
                            .cornerRadius(10)
                            
                        }
                    }
                }
                .padding(.horizontal,6)
                // .padding(.top, 4)
                .padding(.bottom, 4)
            }
            
        }
        .background(Color(red: 238/255, green: 238/255, blue: 238/255)
        )
        
        .onAppear {
            
            getPost()
           // fetchRemoteImage("")
        }
        
    }
    
    
    func returnImg(urlString:String)-> Image{
        
//        if let url_s = URL(string: url) {
//            print(url_s)
//            if let data = try? Data(contentsOf: url_s) {
//                print(data)
//                if let image = UIImage(data: data) {
//                    return Image(uiImage: image)
//                }
//            }
//        }
//        return Image(systemName: "heart.fill")
        guard let url = URL(string: urlString),
              let data = try? Data(contentsOf: url),
              let uiImage = UIImage(data: data)
        else {
            print("Failed to load image from URL: \(urlString)")
            return Image(systemName: "photo")
        }

       // print("Loaded image from URL: \(urlString)")
        return Image(uiImage: uiImage)
    }
}
struct IndexView_Previews: PreviewProvider {
  static var previews: some View {
      IndexView()
  }
}


//class IndexProvider: ObservableObject {
//    var posts: [Post] = []
//    func requestPosts(completion: @escaping (Result<[Post], Error>) -> Void) {
//        // 您的网络请求代码
//        index_provider.request(.getPost)
//                { result in
//                    switch result {
//                    case let .success(response):
//                        do {
//                            let decodedSkinData = try JSONDecoder().decode(PostResponse.self, from: response.data)
//                                print(decodedSkinData)
//
//                            for skinData in decodedSkinData.content {
//                                let post = Post(image: skinData.urls[0], body: skinData.body)
//                                self.posts.append(post)
//                            }
//                            completion(.success(self.posts))
//
//
//                                            }catch let error{
//                                                print(error)
//                        }
//                    case let .failure(error):
//                        print(error)
//                    }
//                }
//    }
//}
